<template>
    <div>
        <el-upload :action="uploadUrl" :file-list="files" :headers="headers" list-type="picture-card"
            :before-upload="befor" :on-success="uploadSuccess">
            <i class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
                <template v-if="isImageOrVideo(file.url) === 'image'">
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                </template>
                <template v-else>
                    <video class="el-upload-list__item-thumbnail" :src="file.url" controls="controls"></video>
                </template>
                
                <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-delete" @click="remove(file)">
                        <i class="el-icon-delete"></i>
                    </span>
                </span>
            </div>
        </el-upload>
    </div>
</template>

<script>
import request from '@/utils/request'
import { Session } from '@/utils/storage'
import { isImageOrVideo } from '@/utils/utils'
export default {
    model: {
        props: 'value',
        event: 'modelChange'
    },
    props: {
        count: {
            type: Number,
            default: 1
        },
        value: {
            type: Array | String,
            default: '',
            required: true
        }
    },
    data() {
        return {
            uploadUrl: '',
            files: [],
            headers: {}
        }
    },
    computed: {
        canUpload() {
            return this.files.length < this.count
        }
    },
    watch: {

    },
    mounted() {
        this.headers = { 'Authorization': `Bearer ${Session.get('token')}` }
        this.uploadUrl = request.defaults.baseURL + '/upload/admin'
        this.setFiles()
    },
    methods: {
        isImageOrVideo(url){
            return isImageOrVideo(url)
        },
        setFiles() {
            if (Array.isArray(this.value)) {
                this.files = this.value.map(e => { return { name: 'file', url: e } })
            }
            else {
                if(!this.value) return
                this.files = [{ name: 'file', url: this.value }]
            }
        },
        uploadSuccess(e) {
            this.files.push({ name: 'file', url: e.data })
            this.end()
        },
        befor(e) {
            if (!this.canUpload) {
                this.$message.error('最多上传' + this.count + '个文件')
                return false
            }
        },
        remove(e) {
            let index = this.files.findIndex(x => x.uid === e.uid)
            this.files.splice(index, 1)
        },
        end() {
            if(this.count === 1){
                this.$emit('modelChange', this.files[0].url)
            }
            else{
                this.$emit('modelChange', this.files.map(e => e.url))
            }
        }
    }
}
</script>